import { LogHelper } from "../utils/logHelper"

export class BuildCheckTask implements IRoomTask {
  run(room: Room): void {
    if (!room.my()) {
      return;
    }

    const role = "build";
    const constructions = new Set<Id<ConstructionSite>>(room.memory.constructions || []);
    const repairs = new Set<Id<Structure>>(room.memory.repairs || []);

    // 检查房间内所有未完成的工地
    if (constructions.size === 0) {
      const newConstructions = room.find(FIND_MY_CONSTRUCTION_SITES);
      newConstructions.forEach((construction) => {
        constructions.add(construction.id);
      });
    }

    // 检查房间内所有需要修复的建筑
    if (repairs.size === 0) {
      // 如果房间内有tower 修复工作交给tower
      const towers = room.find(FIND_MY_STRUCTURES).filter((structure)=> structure.structureType === STRUCTURE_TOWER);
      if(towers.length === 0){
        const structures = room.find(FIND_STRUCTURES, {
          filter: (structure) => {
            return (
              structure.structureType !== STRUCTURE_RAMPART &&
              structure.structureType !== STRUCTURE_WALL &&
              structure.hits < structure.hitsMax &&
              structure.hits / structure.hitsMax < 0.4
            );
          }
        });
        structures.forEach((structure) => {
          repairs.add(structure.id);
        });
      }
    }

    // 只有在更新了数据后，才需要将它们重新赋值给 room.memory 对象
    if (constructions.size !== room.memory.constructions?.length || repairs.size !== room.memory.repairs?.length) {
      room.memory.constructions = Array.from(constructions);
      room.memory.repairs = Array.from(repairs);
    }

    if (repairs.size > 0 || constructions.size > 0) {
      const creeps = Object.values(Game.creeps).filter((creep) =>
        creep.memory.role === role &&
        creep.memory.outerRoom &&
        creep.memory.outerRoom === room.name
      );
      const queueCreeps = room.spawnQueueGetRole(role,(creeps) => creeps.memory.outerRoom !== undefined && creeps.memory.outerRoom === room.name);
      const spawn = room.spawn();
      const buildIndexCount = creeps.length + queueCreeps.length;
      const buildNeedCount = buildIndexCount == 0 ? 1 : Math.ceil(constructions.size / 5);
      if(spawn){
        if(buildIndexCount < buildNeedCount && !spawn.spawning){
          const controllerLevel = room.controller?.level;
          if(controllerLevel){
            const body = room.calculateCreepBody({
              [WORK]: 0.4,
              [MOVE]: 0.3,
              [CARRY]: 0.3,
            });
            if(body){
              for (let index = 0; index < (buildNeedCount - buildIndexCount); index++) {
                room.spawnQueueAdd(role,body,{ role, bornRoom:room.name, outerRoom:room.name });
                LogHelper.log(`房间管理[${room.name}] 申请孵化 ${role}`);
              }
            }
          }
        }
      }
    }
  }
}